package com.lagou.nio.buffer;

import java.nio.ByteBuffer;

/**
 * Buffer的读取
 */
public class GetBufferDemo {

    private static void print(ByteBuffer allocate, String msg) {
        System.out.println(msg);
        System.out.println("当前索引所在的位置: " + allocate.position());
        System.out.println("最多能操作索引个数: " + allocate.limit());
        System.out.println("缓冲区的总长度: " + allocate.capacity());
        System.out.println("还能操作的索引个数: " + allocate.remaining());
        System.out.println("是否还能操作缓冲区: " + allocate.hasRemaining());
        System.out.println("==========================");
    }

    public static void main(String[] args) {
        ByteBuffer allocate = ByteBuffer.allocate(10);
        allocate.put("abcd".getBytes());
        print(allocate, "===创建buffer");
        //切换读模式
        allocate.flip();
        for (int i = 0; i < allocate.limit(); i++) {
            System.out.println((char) allocate.get());
        }
        print(allocate, "===读取buffer");
        //System.out.println((char) allocate.get());
        //读取自定索引的值
        System.out.println((char) allocate.get(1));
        //读取多个字节
        allocate.rewind();
        byte[] bytes = new byte[4];
        allocate.get(bytes);
        System.out.println(new String(bytes));
        //将缓存区转换字节数组返回
        byte[] array = allocate.array();
        System.out.println(new String(array));
        //切换写模式
        allocate.clear();
        print(allocate, "===切换写模式");
        allocate.put("123".getBytes());
        print(allocate, "===创建buffer");
        array = allocate.array();
        System.out.println(new String(array));
    }
}
